﻿using System.Configuration;
using System.Collections.Generic;

namespace Sissonix.ExtRest.Configuration
{
    public class DomainsElementCollection : ConfigurationElementCollection
    {
        Dictionary<string, string> pathClasses = new Dictionary<string,string>();

        public DomainElement this[int index]
        {
            get
            {
                return base.BaseGet(index) as DomainElement;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

        public string GetProcessingClassName(string domainRoot)
        {
            if ( !pathClasses.ContainsKey(domainRoot) ) {
                foreach (ConfigurationElement ce in this)
                {
                    DomainElement d = (DomainElement)ce;
                    if (d.DomainRoot == domainRoot)
                    {
                        pathClasses.Add(domainRoot, d.ProcessingClass);
                        break;
                    }
                }
            }
            return pathClasses[domainRoot];
        }

        public string GetDomainRoot(string domainRoot)
        {
            if (!pathClasses.ContainsKey(domainRoot))
            {
                foreach (ConfigurationElement ce in this)
                {
                    DomainElement d = (DomainElement)ce;
                    if (d.DomainRoot == domainRoot)
                    {
                        pathClasses.Add(domainRoot, d.ProcessingClass);
                        break;
                    }
                }
            }
            return pathClasses[domainRoot];
        }


        protected override ConfigurationElement CreateNewElement()
        {
            return new DomainElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((DomainElement)element).DomainRoot;
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
        }
    }


}
